'''
Created on 2014-5-19

@author: ASUS
'''
from fetch_info_to_file.get_category import Category
from fetch_info_to_file.get_ASIN import get_ASIN
import json

import urllib

class AllProducts_Reviews():
   
    def download_reviews(self):
        C = Category()
        cate = C.get_all_categories()
        A=get_ASIN()
        for single in cate[61:90]:
            temp=single['name']
            temp.replace(' ','%20') 
            temp.replace('&','$')
            temp.replace('>','%3')
            product_num = int(json.loads(urllib.urlopen('http://112.124.1.3:8004/api/commodity/count/?category_name='+temp).read())['count'])  
            page=1
            if product_num>20:
                page=product_num/20
            for i in (0,page):
                l=A.get(single['name'].replace('&','$'),i)
                for asin in l:
                    self.getReviewInfo(asin,single['name'])
                
                
    def seperate_time(self,time_str):
        year_month_day=time_str.split(' ')[0]
        hour_minute_second=time_str.split(' ')[1]
        time={'year':year_month_day.split('-')[0],'month':year_month_day.split('-')[1],
              'day':year_month_day.split('-')[2],'hour':hour_minute_second.split(':')[0],
              'minute':hour_minute_second.split(':')[1]}
        return time            
            
    def get_product_data(self,info):  
        target_url = 'http://112.124.1.3:8004/api/commodity/' + info + '/'
        return json.loads(urllib.urlopen(target_url).read())
    
    def getReviewInfo(self,info,category):  
        product_data = self.get_product_data(info)
        Asin = product_data['ASIN']
        review_count = product_data['stats_info']['review_count']
        single_reviews = []

        for number in range(0, review_count):
            publish_time=product_data['review'][number]['publishTime']
            rank=product_data['review'][number]['star'].split('.')[0]
            consumer=product_data['review'][number]['consumer']
            single_reviews.append({'time':self.seperate_time(publish_time),'rank':rank,'consumer':consumer})                      
        review = {'Category':category,'ASIN': Asin, 'single_review':single_reviews}
        review_str=str(review)
        #f=open(r'../txt_package/women_jeans_review_count.txt','a')
       # print Asin+'  '+str(review_count)
        #f.write(str(review_count))

       # f.close()
        file=open(r'../txt_package/reviews_with_category.txt','a')
        file.write(review_str)

        file.write('\n')
        file.close()
    
    def getPurchased(self,consumer):
        purchase_record=[]
        info=self.readFromLocal()
        for single in info:
            reviews=single['single_review']
            for one in reviews:
                if one['consumer']==consumer:
                    purchased={'ASIN':single['ASIN'],'time':one['time']}
                    purchase_record.append(single['ASIN'])
        file.close()    
             
        return purchased
            
    def calDistance(self,asin):
        R=10000
        
        return 0
    
    def storeGuess(self):
        return 0
    
    def readFromLocal(self):
        info=[]
        file=open(r'../txt_package/reviews_with_category_2.txt','r')
        while True:
            line=file.readline()
            if line:
                info.append(eval(line))
            else:
                break
        
        return info
    
if __name__ == '__main__':
    A=AllProducts_Reviews()
    file=open(r'../txt_package/useful_reviews_2.txt','a')
    for single in A.readFromLocal():
        if single['single_review']:
            file.write(str(single))
            file.write('\n')
        else:
            continue
    file.close
